package simple;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

public class ProducerDemo {
    public static void main(String[] args) throws IOException, TimeoutException {
        //建立连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("139.199.198.28"); //ip 地址
        connectionFactory.setPort(5672); //端口号
        connectionFactory.setUsername("admin"); //用户名
        connectionFactory.setPassword("admin"); //密码
        connectionFactory.setVirtualHost("/"); //虚拟主机
        Connection connection = connectionFactory.newConnection();

        //开启信道
        Channel channel = connection.createChannel();

        //声明交换机，此处使用内置交换机

        //声明队列
        /**
         * queueDeclare(
         * String queue,  队列名称
         * boolean durable,  可持久化
         * boolean exclusive,  独占
         * boolean autoDelete,  自动删除
         * Map<String, Object> arguments 参数
         * )
         */
        channel.queueDeclare("hello", true, false, false, null);

        //发送消息
        /**
         * basicPublish(
         * String exchange, 交换机名称
         * String routingKey,  与要使用的队列名保持一直
         * BasicProperties props,  属性配置
         * byte[] body 消息内容
         * )
         */
        String messageInfo = "hello mq";
        channel.basicPublish("", "hello", null, messageInfo.getBytes(StandardCharsets.UTF_8));

        //资源释放
        //先释放 channel ，后释放 connection，顺序反了会报错
        channel.close();
        connection.close(); // connection 关闭后，包含的 channel 也就关闭了
    }
}
